package net.tooeye.easymes.common;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import java.util.Collections;
import java.util.HashMap;
import java.util.IllegalFormatCodePointException;
import java.util.Map;


//有时间改成通过HTTP CODE  RESTFUL的版本

public class NetworkUtil {
    private static NetworkUtil instance;
    private RequestQueue mRequestQueue = EasyApp.sRequestQueue;

    public static NetworkUtil getInstance() {
        if (instance == null) {
            synchronized (NetworkUtil.class) {
                if (instance == null) {
                    instance = new NetworkUtil();
                }
            }
        }
        return instance;
    }

    //发送POST请求
    public void post(final Activity activity, String url, final Map<String, String> map, final Handler handler, final int tag,final String token) {
        request(activity,url,map,handler,tag,Request.Method.POST,token);
    }

    //发送GET请求
    public void get(final Activity activity, String url, final Map<String, String> map, final Handler handler, final int tag,final String token) {
        request(activity,url,map,handler,tag,Request.Method.GET,token);
    }

    //发送PUT请求
    public void put(final Activity activity, String url, final Map<String, String> map, final Handler handler, final int tag,final String token) {
        request(activity,url,map,handler,tag,Request.Method.PUT,token);
    }

    //发送PUT请求
    public void delete(final Activity activity, String url, final Map<String, String> map, final Handler handler, final int tag,final String token) {
        request(activity,url,map,handler,tag,Request.Method.DELETE,token);
    }

    private  void  request(final Activity activity, String url, final Map<String, String> map, final Handler handler, final int tag,final int method,final String token) {
        final ProgressDialog dialog = new ProgressDialog(activity);
        dialog.setTitle("正在连接");
        dialog.setCancelable(false);
        if (!dialog.isShowing()) {
            dialog.show();
        }
        final Message message = Message.obtain();
        StringRequest request = new StringRequest(method, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                message.what = tag;
                message.obj =  s;
                handler.sendMessage(message);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                try{
                    byte[] htmlBodyBytes = volleyError.networkResponse.data;
                    String serverMessage = new String(htmlBodyBytes);
                    int errorCode = volleyError.networkResponse.statusCode;
                    if (errorCode == 403){
                        Toast.makeText(activity,"没有登录或登录过期:"+ serverMessage+"code:"+errorCode,Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (errorCode == 404){
                        Toast.makeText(activity,"没有找到对应的地址:"+ serverMessage+"code:"+errorCode,Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (errorCode == 400){
                        Toast.makeText(activity,"错误请求，或参数错误:"+ serverMessage+"code:"+errorCode,Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (errorCode == 405){
                        Toast.makeText(activity,"没有权限:"+ serverMessage+"code:"+errorCode,Toast.LENGTH_LONG).show();
                        return;
                    }
                    Log.d("错",volleyError.toString());
                    Toast.makeText(activity,"网络其他错误"+ serverMessage+"code:"+errorCode,Toast.LENGTH_LONG).show();
                }
                catch(Exception e){
                    Toast.makeText(activity,"服务器出现问题",Toast.LENGTH_LONG).show();
                }

            }
        }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = super.getHeaders();
                if (headers == null || headers.equals(Collections.<String, String>emptyMap())){
                    headers = new HashMap<>();
                }
                headers.put("token",token);
                return headers;
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(
                20 * 1000,//链接超时时间
                0,//重新尝试连接次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT//曲线增长因子
        ));
        mRequestQueue.add(request);
    }


}
